import 'package:check_app/dao/addTask_dao.dart';
import 'package:check_app/dao/task_dao.dart';
import 'package:check_app/page/AddTaskPage.dart';
import 'package:check_app/scoped_model/app_model.dart';
import 'package:check_app/util/pref_util.dart';
import 'package:check_app/util/uploadImage_util.dart';
import 'package:check_app/widgets/NoSignal.dart';
import 'package:check_app/widgets/deleteModal.dart';
import 'package:check_app/widgets/downModal.dart';
import 'package:flutter/material.dart';
import 'package:check_app/widgets/PictureOffline.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:scoped_model/scoped_model.dart';
import 'dart:convert' as convert;

class TaskDetailPage extends StatefulWidget {
  final int id;
  final int customerId;
  final int guideBookId;
  final String type;
  final String code;
  final String contractNo;
  final String status;
  final String customerName;
  final String guideBookName;
  final String provinceName;
  final String provinceCode;
  final String cityName;
  final String cityCode;
  final String countyName;
  final String countyCode;
  final int checkQuantity;
  final List operatorList;
  final List proofUrlList;
  const TaskDetailPage({
    Key key,
    this.id,
    this.customerId,
    this.guideBookId,
    this.type,
    this.code,
    this.contractNo,
    this.status,
    this.customerName,
    this.guideBookName,
    this.checkQuantity,
    this.operatorList,
    this.proofUrlList,
    this.provinceName,
    this.provinceCode,
    this.cityName,
    this.cityCode,
    this.countyName,
    this.countyCode,
  }) : super(key: key);
  @override
  State<StatefulWidget> createState() => new _TaskDetailPageState();
}

class _TaskDetailPageState extends State<TaskDetailPage> {
  bool _loading = false;
  int id;
  List<Map> infoList;
  List proofUrlList;
  Map<String, String> infoData;

  @override
  void initState() {
    super.initState();
    var list = widget.operatorList.map((item) => item.operatorName).toList();
    infoData = {
      'code': widget.code,
      'contractNo': widget.contractNo,
      'customerName': widget.customerName,
      'guideBookName': widget.guideBookName,
      'check': list.join('，'),
      'checkQuantity': widget.checkQuantity.toString(),
      'address': (widget.provinceName.toString() ?? '--') +
          '/' +
          (widget.cityName.toString() ?? '--') +
          '/' +
          (widget.countyName.toString() ?? '--'),
    };
    infoList = [
      {
        'title': '任务编码',
        'key': 'code',
      },
      {
        'title': '合同编码',
        'key': 'contractNo',
      },
      {
        'title': '所属客户',
        'key': 'customerName',
      },
      {
        'title': '作业指导书',
        'key': 'guideBookName',
      },
      {
        'title': '检察员',
        'key': 'check',
      },
      {
        'title': '检验地址',
        'key': 'address',
      },
      {
        'title': '检验数量',
        'key': 'checkQuantity',
      },
    ];
    id = widget.id;
    proofUrlList = widget.proofUrlList ?? [];
  }

  Future<Null> editNormalTask() async {
    setState(() {
      _loading = true;
    });
    final netList = await UploadImageUtil().getImageNetUrl(proofUrlList);
    final taskInfo = await PrefUtil().getString('task_' + id.toString());
    if (taskInfo != null) {
      var taskInfoMap = convert.jsonDecode(taskInfo);
      taskInfoMap['proofUrlList'] = netList;
      await PrefUtil()
          .setString('task_' + id.toString(), convert.jsonEncode(taskInfoMap));
    }
    try {
      var result = await TaskDao.editNormalTask({
        "id": widget.id.toString(),
        "proofUrlList": netList,
      });
      setState(() {
        _loading = false;
        proofUrlList = netList;
      });
      if (result.success) {
        Navigator.of(context).pop();
      } else {
        Fluttertoast.showToast(
          msg: result.message,
        );
      }
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
    }
    return null;
  }

  Future<Null> editExtraTask() async {
    setState(() {
      _loading = true;
    });
    final netList = await UploadImageUtil().getImageNetUrl(proofUrlList);
    final taskInfo = await PrefUtil().getString('task_' + id.toString());
    if (taskInfo != null) {
      var taskInfoMap = convert.jsonDecode(taskInfo);
      taskInfoMap['proofUrlList'] = netList;
      await PrefUtil()
          .setString('task_' + id.toString(), convert.jsonEncode(taskInfoMap));
    }
    try {
      var result = await AddTaskDao.add({
        "code": widget.code,
        "contractNo": widget.contractNo,
        "customerId": widget.customerId.toString(),
        "guideBookId": widget.guideBookId.toString(),
        "id": widget.id.toString(),
        "proofUrlList": netList,
        "provinceName": widget.provinceName,
        "provinceCode": widget.provinceCode,
        "cityName": widget.cityName,
        "cityCode": widget.cityCode,
        "countyName": widget.countyName,
        "countyCode": widget.countyCode,
      });
      setState(() {
        _loading = false;
        proofUrlList = netList;
      });
      if (result.success) {
        Navigator.of(context).pop();
      } else {
        Fluttertoast.showToast(
          msg: result.message,
        );
      }
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
      Fluttertoast.showToast(
        msg: "网络错误",
      );
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('任务详情'),
        actions: <Widget>[
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () async {
              print(id);
              await Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                return AddTaskPage(
                  code: widget.code + '-01',
                  contractNo: widget.contractNo,
                  customerId: widget.customerId,
                  customerName: widget.customerName,
                  guideBookId: widget.guideBookId,
                  guideBookName: widget.guideBookName,
                  provinceName: widget.provinceName,
                  provinceCode: widget.provinceCode,
                  cityName: widget.cityName,
                  cityCode: widget.cityCode,
                  countyName: widget.countyName,
                  countyCode: widget.countyCode,
                );
              }));
            },
            child: Container(
              alignment: Alignment.center,
              padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
              child: Text('复制'),
            ),
          ),
        ],
      ),
      body: SafeArea(
        child: ModalProgressHUD(
          inAsyncCall: _loading,
          child: Stack(
            children: <Widget>[
              Container(
                padding: EdgeInsets.fromLTRB(16, 0, 16, 0),
                child: Column(
                  children: <Widget>[
                    NoSignal(),
                    Container(
                      padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
                      decoration: BoxDecoration(
                        border: Border(
                          bottom: BorderSide(
                            width: 1,
                            color: Color.fromRGBO(229, 229, 229, 1),
                          ),
                        ),
                      ),
                      child: Column(
                        children: getInfoList(infoList),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 8),
                      child: Column(
                        children: <Widget>[
                          Container(
                            alignment: Alignment.centerLeft,
                            margin: EdgeInsets.only(top: 12, bottom: 12),
                            child: Text(
                              '原始凭证',
                              style: TextStyle(
                                  fontSize: 14,
                                  height: 20 / 14,
                                  color: Color.fromRGBO(150, 151, 154, 1)),
                            ),
                          ),
                          Picture(
                            count: 4,
                            picList: proofUrlList,
                            uploadButton: widget.status != 'FINISH',
                            onAdd: () {
                              showModalBottomSheet(
                                context: context,
                                builder: (BuildContext context) {
                                  return DownModal(
                                    cameraCb: () async {
                                      final connectionStatus =
                                          ScopedModel.of<GlobalModel>(context)
                                              .connectionStatus;
                                      if (connectionStatus ==
                                          'ConnectivityResult.none') {
                                        final url = await UploadImageUtil()
                                            .saveImageFromCamera();
                                        print(url);
                                        setState(() {
                                          proofUrlList.add(url);
                                          _loading = false;
                                        });
                                      } else {
                                        final url = await UploadImageUtil()
                                            .getImageFromCamera();
                                        setState(() {
                                          proofUrlList.add(url);
                                          _loading = false;
                                        });
                                      }
                                    },
                                    photoCb: () async {
                                      final connectionStatus =
                                          ScopedModel.of<GlobalModel>(context)
                                              .connectionStatus;
                                      if (connectionStatus ==
                                          'ConnectivityResult.none') {
                                        final urlList = await UploadImageUtil()
                                            .saveImageFromGallery(
                                                9 - proofUrlList.length);
                                        print(urlList);
                                        setState(() {
                                          for (var value in urlList) {
                                            proofUrlList.add(value.toString());
                                          }
                                          _loading = false;
                                        });
                                      } else {
                                        final urlList = await UploadImageUtil()
                                            .loadAssets(
                                                9 - proofUrlList.length);
                                        print(urlList);
                                        setState(() {
                                          for (var value in urlList) {
                                            proofUrlList.add(value.toString());
                                          }
                                          _loading = false;
                                        });
                                      }
                                    },
                                  );
                                },
                              );
                            },
                            onRemove: (url) {
                              if (widget.status == 'FINISH') return null;
                              showModalBottomSheet(
                                context: context,
                                builder: (BuildContext context) {
                                  return DeleteModal(
                                    onRemove: () {
                                      setState(() {
                                        proofUrlList.remove(url);
                                      });
                                    },
                                  );
                                },
                              );
                            },
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
              widget.status != 'FINISH'
                  ? Positioned(
                      left: 0,
                      right: 0,
                      bottom: 24,
                      child: Container(
                        padding: EdgeInsets.fromLTRB(16, 0, 16, 0),
                        width: double.infinity,
                        child: MaterialButton(
                          onPressed: () async {
                            final connectionStatus =
                                ScopedModel.of<GlobalModel>(context)
                                    .connectionStatus;
                            if (connectionStatus == 'ConnectivityResult.none') {
                              print('保存本地');
                              final taskInfo = await PrefUtil()
                                  .getString('task_' + id.toString());

                              if (taskInfo != null) {
                                print('本地有任务数据');
                                var taskInfoMap = convert.jsonDecode(taskInfo);
                                taskInfoMap['proofUrlList'] = proofUrlList;
                                await PrefUtil().setString(
                                    'task_' + id.toString(),
                                    convert.jsonEncode(taskInfoMap));
                              } else {
                                print('本地无任务数据');
                                final taskInfo =
                                    await PrefUtil().getString('taskInfo');
                                var taskInfoMap = convert.jsonDecode(taskInfo);
                                taskInfoMap['proofUrlList'] = proofUrlList;
                                await PrefUtil().setString(
                                    'task_' + id.toString(),
                                    convert.jsonEncode(taskInfoMap));
                              }
                              Navigator.of(context).pop();
                            } else {
                              if (widget.type == 'NORMAL') {
                                editNormalTask();
                              } else if (widget.type == 'EXTRA') {
                                editExtraTask();
                              }
                            }
                          },
                          color: Colors.blue,
                          textColor: Colors.white,
                          height: 44,
                          child: Text(
                            '保存',
                            style: TextStyle(
                              fontSize: 14,
                              height: 24 / 17,
                            ),
                          ),
                        ),
                      ),
                    )
                  : SizedBox(),
            ],
          ),
        ),
      ),
    );
  }

  handleAddress(text) {
    if (text == 'address') {
      return infoData['provinceName'] ??
          '--' + '/' + infoData['cityName'] ??
          '--' + '/' + infoData['countyName'] ??
          '--';
    } else {
      return infoData[text] ?? '--';
    }
  }

  // 获取菜单项widget列表
  List<Widget> getInfoList(List info) {
    return info.map<Widget>((item) => createInfoItem(item)).toList();
  }

  // 生成单个菜单项
  Widget createInfoItem(item) {
    return Container(
      height: 40,
      child: Row(
        children: <Widget>[
          Container(
            alignment: Alignment.centerLeft,
            child: Text(
              item['title'],
              style: TextStyle(
                fontSize: 14,
                height: 20 / 14,
                color: Color.fromRGBO(150, 151, 154, 1),
              ),
            ),
          ),
          Expanded(
            child: Container(
              alignment: Alignment.centerRight,
              child: Text(
                infoData[item['key']] ?? '--',
                style: TextStyle(
                  fontSize: 14,
                  height: 20 / 14,
                  color: Color.fromRGBO(43, 44, 46, 1),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
